/* eslint-disable */
import plupload from "plupload";

class Poupload {
  constructor() {
    this.accessid = ''
    this.host = ''
    this.policyBase64 = ''
    this.signature = ''
    this.callbackbody = ''
    this.key = ''
    this.expire = 0
    this.g_object_name = ''
    this.g_object_name_type = 'local_name'
    this.timestamp = Date.parse(new Date()) / 1000
    this.now = this.timestamp
  }

  send_request(serverUrl) {
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
      xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlhttp!=null)
    {
      // serverUrl是 用户获取 '签名和Policy' 等信息的应用服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
      // serverUrl = 'http://88.88.88.88:8888'
      // let serverUrl = 'https://invitation-pc-test.crehopson.com/business-invitation/v1/api/test/sign?fileName=1&fileType=jpg&fileSize=1'

      xmlhttp.open( "GET", serverUrl, false );
      xmlhttp.send( null );
      return xmlhttp.responseText
    }
    else
    {
      alert("Your browser does not support XMLHTTP.");
    }
  };

  check_object_radio() {
    var tt = document.getElementsByName('myradio');
    for (var i = 0; i < tt.length ; i++ )
    {
      if(tt[i].checked)
      {
        this.g_object_name_type = tt[i].value;
        break;
      }
    }
  }

  get_signature(serverUrl) {
    // 可以判断当前expire是否超过了当前时间， 如果超过了当前时间， 就重新取一下，3s 作为缓冲。
    this.now = this.timestamp = Date.parse(new Date()) / 1000;
    if (this.expire < this.now + 3)
    {
      let body = this.send_request(serverUrl)
      // console.log(body)
      var obj = eval ("(" + body + ")");
      // console.log('obj', obj)
      var dataObj = obj['data']
      // console.log('dataObj', dataObj)
      this.host = dataObj['host']
      this.policyBase64 = dataObj['policy']
      this.accessid = dataObj['accessid']
      this.signature = dataObj['signature']
      this.expire = parseInt(dataObj['expire'])
      this.callbackbody = dataObj['callback']
      this.key = dataObj['dir']
      return true;
    }
    return false;
  }

  random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (let i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }

  get_suffix(filename) {
    let pos = filename.lastIndexOf('.')
    let suffix = ''
    if (pos != -1) {
      suffix = filename.substring(pos)
    }
    return suffix;
  }

  calculate_object_name(filename) {
    if (this.g_object_name_type == 'local_name')
    {
      this.g_object_name += "${filename}"
    }
    else if (this.g_object_name_type == 'random_name')
    {
      let suffix = this.get_suffix(filename)
      this.g_object_name = this.key + this.random_string(10) + suffix
    }
    return ''
  }

  get_uploaded_object_name(filename) {
    if (this.g_object_name_type == 'local_name')
    {
      let tmp_name = this.g_object_name
      tmp_name = tmp_name.replace("${filename}", filename);
      return tmp_name
    }
    else if(this.g_object_name_type == 'random_name')
    {
      return this.g_object_name
    }
  }

  set_upload_param(up, filename, ret, serverUrl) {
    if (ret == false)
    {
      ret = this.get_signature(serverUrl)
    }
    this.g_object_name = this.key;
    if (filename != '') {
      let suffix = this.get_suffix(filename)
      this.calculate_object_name(filename)
    }
    let new_multipart_params = {
      'key' : this.g_object_name,
      'policy': this.policyBase64,
      'OSSAccessKeyId': this.accessid,
      'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
      'callback' : this.callbackbody,
      'signature': this.signature,
    };

    up.setOption({
      'url': this.host,
      'multipart_params': new_multipart_params
    });

    up.start();
  }
}

export const initPoupload = ({ containerId, serverUrl, fileExts,onUploadComplete, onUploadProgress, onShowProgress,onUploadCompleteFiles }) => {
  const poupload = new Poupload()

  var uploader = new plupload.Uploader({
    runtimes : 'html5,flash,silverlight,html4',
    browse_button : containerId +'_selectfiles',
    //multi_selection: false,
    container: document.getElementById(containerId),
    // flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
    // silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
    url : 'http://oss.aliyuncs.com',
    filters: {
      mime_types : [ //只允许上传图片和zip文件
        { title : "Common files", extensions : fileExts },
        // { title : "Zip files", extensions : "zip,rar" }
      ],
      max_file_size : '100mb', //最大只能上传10mb的文件
      prevent_duplicates : true //不允许选取重复文件
    },

    init: {
      PostInit: function() {
        // set_upload_param 在 FilesAdded 里直接调用，不用点击按钮 click 了，这里基本执行不到了。
        /*document.getElementById('ossfile').innerHTML = '';
        document.getElementById('postfiles').onclick = function() {
            set_upload_param(uploader, '', false);
            return false;
        };*/
      },

      FilesAdded: function(up, files) {
        // 这里是设置选择文件的显示
        /*plupload.each(files, function(file) {
            document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
                +'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
                +'</div>';
        });*/

        // 提交文件，参考PostInit里绑定的 onclick 方法
        poupload.set_upload_param(uploader, '', false, serverUrl);
        // 上传之前弹出进度条
        if (typeof onShowProgress === 'function') {
          onShowProgress(true)
        }
      },

      BeforeUpload: function(up, file) {
        poupload.check_object_radio();
        poupload.set_upload_param(up, file.name, true, serverUrl);
      },

      UploadProgress: function(up, file) {
        // 这里是进度条，需要的话，再自己设置
        /*var d = document.getElementById(file.id);
        d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
        var prog = d.getElementsByTagName('div')[0];
        var progBar = prog.getElementsByTagName('div')[0]
        progBar.style.width= 2*file.percent+'px';
        progBar.setAttribute('aria-valuenow', file.percent);*/
        console.log(containerId + " file " + file.name + " progress=" + file.percent + "%")
        if (typeof onUploadProgress === 'function') {
          onUploadProgress(file.percent)
        }
      },

      FileUploaded: function(up, file, info) {
        // FilesAdded 里把选择文件的显示注释掉了，所以这里的 getElementsByTagName 会报错。其实自定义也不需要这个，注释掉。状态自己判断修改即可
        /*if (info.status == 200)
        {
            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'upload to oss success, object name:' + get_uploaded_object_name(file.name) + ' 回调服务器返回的内容是:' + info.response;
        }
        else if (info.status == 203)
        {
            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传到OSS成功，但是oss访问用户设置的上传回调服务器失败，失败原因是:' + info.response;
        }
        else
        {
            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
        }*/

        if (info.status == 200) {
          console.log(containerId + ' upload to oss success, object name:' + file.name + ' 回调服务器返回的内容是:' + info.response)
          if (typeof onUploadCompleteFiles === 'function') {
            onUploadCompleteFiles(info.response)
          }
        } else if (info.status == 203) {
          console.log(containerId + ' 上传到OSS成功，但是oss访问用户设置的上传回调服务器失败，失败原因是:' + info.response)
        } else {
          console.log(containerId + ' ' + info.response)
        }
      },
      UploadComplete: function(uploader,files) {
        console.log(containerId + ' UploadComplete files is', files)
        if (typeof onUploadComplete === 'function') {
          onUploadComplete(files)
        }
      },
      Error: function(up, err) {
        /*if (err.code == -600) {
            document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小"));
        }
        else if (err.code == -601) {
            document.getElementById('console').appendChild(document.createTextNode("\n选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型"));
        }
        else if (err.code == -602) {
            document.getElementById('console').appendChild(document.createTextNode("\n这个文件已经上传过一遍了"));
        }
        else
        {
            document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
        }*/

        if (err.code == -600) {
          console.log(containerId + " 选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小");
        } else if (err.code == -601) {
          console.log(containerId + " 选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型");
        } else if (err.code == -602) {
          console.log(containerId + " 这个文件已经上传过一遍了");
        } else {
          console.log(containerId + " Error xml:" + err.response);
        }
      }
    }
  });

  uploader.init();
}
